package edu.uwosh.cs342.placestobe;


import java.util.ArrayList;
import java.util.StringTokenizer;


import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class InvitesActivity extends Activity{
	ArrayList<Invite> allInvites= new ArrayList<Invite>();
	Spinner spin;
	TextView tv;
	TextView dateView;
	RadioButton rbA;
	RadioButton rbB; 
	Button but;
	ArrayList<CharSequence> meets;
	int selectedPos;
	boolean attending;
	String attend;
	String notAttend;
	ArrayList<Integer> statusi;
	
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.invites);
		spin = (Spinner) findViewById(R.id.spinnerEvents);
		tv = (TextView) findViewById(R.id.textViewDescription);
		dateView = (TextView) findViewById(R.id.textViewDate);
		rbA = (RadioButton) findViewById(R.id.radioAttend);
		rbB = (RadioButton) findViewById(R.id.radioNotAttend);
		but = (Button) findViewById(R.id.buttonSubmit);
		statusi = new ArrayList<Integer>();
		meets = new ArrayList<CharSequence>();
		
		
		ArrayList<CharSequence> x = new ArrayList<CharSequence>();
		x.add("Pizza");
		x.add("notes");
		
		

	}
	
	@Override
	public void onResume() {
		super.onResume();
		new AsyncGetInvites().execute((Object[]) null);
	}
	
	@Override
	protected void onPause(){
        super.onPause();
        allInvites.clear();
        meets.clear();
    }
	
	public void initializeSpinner(){
		ArrayAdapter<CharSequence> adapter  = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, meets);
		adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spin.setAdapter(adapter);
		spin.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View arg1, 	int pos, long id) {
				selectedPos = pos;
				notAttend = "http://cs346.cs.uwosh.edu/students/blairm83/cs342group6/denyEvent.php?meetID="+allInvites.get(selectedPos).getMeetID()+"&userID="+MainActivity.userID;
				attend = "http://cs346.cs.uwosh.edu/students/blairm83/cs342group6/acceptEvent.php?meetID="+allInvites.get(selectedPos).getMeetID()+"&userID="+MainActivity.userID;
					fillFields(selectedPos);
			}

			public void onNothingSelected(AdapterView<?> arg0) {				
			}
		});
		but.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// SEND DATA TO SERVER
				if(rbA.isChecked()){
					attending = true;
				}else{
					attending = false;
				}
				new AsyncSetStatus().execute((Object[]) null);
			}
		}); 
		
	}
	
	
	
	
	private void fillFields(int i){
		Invite invite = allInvites.get(i);
		dateView.setText(invite.getDate());
		tv.setText(invite.getDescription());
//		String s = invite.getStatus();
		String s = statusi.get(i).toString();
		if(s.equalsIgnoreCase("-1")){
			rbA.setChecked(false);
			rbB.setChecked(true);
			statusi.set(i, -1);
		}else if(s.equalsIgnoreCase("0")){
			rbA.setChecked(false);
			rbB.setChecked(false);
			statusi.set(i, 0);
		}else{
			rbA.setChecked(true);
			rbB.setChecked(false);
			statusi.set(i, 1);
		}
	}
	
	private class AsyncSetStatus extends AsyncTask<Object, Object, Object>{
		String response = "";		
		@Override
		protected Object doInBackground(Object... arg0) {	
			try {  
				if(attending){
					response = attend;
				}else{
					response = notAttend; 
				}
				response = CustomHttpClient.executeHttpGet(response); 
				response = response.toString().trim();
			} catch (Exception e) {  System.out.println(e.toString());}
			return null;
		}
		@Override
		protected void onPostExecute(Object result){
			//toast
			if(response.equalsIgnoreCase("1")){
				String status = "Submitted 'Attending' status";
				statusi.set(selectedPos, 1);
				if(!attending){
					status = "Submitted 'Not Attending' status";
					statusi.set(selectedPos, -1);
				}
				Toast.makeText(getApplicationContext(),status,Toast.LENGTH_LONG).show();
				
			}else{
				Toast.makeText(getApplicationContext(),"Issue sending status update",Toast.LENGTH_LONG).show();
			}
				
			
		}
	}
	
	
	private class AsyncGetInvites extends AsyncTask<Object, Object, Object>{
		String response = "";		
		@Override
		protected Object doInBackground(Object... arg0) {	
			try {  
				response = CustomHttpClient.executeHttpGet("http://cs346.cs.uwosh.edu/students/blairm83/cs342group6/viewUserEvent.php?userID="+MainActivity.userID); 
				response = response.toString().trim();
			} catch (Exception e) {  System.out.println(e.toString());}
			return null;
		}
		@Override
		protected void onPostExecute(Object result){
			allInvites = tokenizeResponse(response);
			fillList(allInvites);
			initializeSpinner();
		}
	}
	
	private ArrayList<Invite> tokenizeResponse(String res){
		ArrayList<Invite> invites = new ArrayList<Invite>();
		if(res.length() > 0){
			//fill shit
			StringTokenizer event = new StringTokenizer(res, "|");
			for(int i = 0; event.hasMoreTokens(); i++){
				String curEvent = event.nextToken();
				StringTokenizer parse = new StringTokenizer(curEvent, "^");					
				invites.add(new Invite(parse.nextToken(), parse.nextToken(), parse.nextToken(), parse.nextToken()));
			}
		}
		return invites;
	}
	
	private void fillList(ArrayList<Invite> invites){
		for(int i = 0; i < invites.size(); i++){
			meets.add(invites.get(i).getDescription());
			statusi.add(Integer.parseInt(invites.get(i).getStatus()));
			System.out.println(statusi.get(i));
		}
	}

	
	class Invite{
		String description = "No invites at this time";
		String date = "";
		String status = "0";
		String meetID = "-1";
		
		Invite(String d, String date, String status,  String meet){
			description = d;
			this.date = date;
			this.status = status;
			meetID = meet;
		}

		public String getDescription() {
			return description;
		}

		public String getDate() {
			return date;
		}

		public String getStatus() {
			return status;
		}

		public String getMeetID() {
			return meetID;
		}
		
		@Override
		public String toString(){
			return description + ", " + date + ", " + status + ", " + meetID;  
		}
	}
	
	
	
	
}
